<template>
  <view class="attendance-stats-page">
    <!-- 导航栏 -->
    <view class="navbar">
      <image 
        class="icon-image" 
        src="/static/icons/arrow-left.svg" 
        mode="aspectFit" 
        @click="goBack"
      />
      <text class="navbar-title">考勤统计</text>
      <view class="navbar-right"></view>
    </view>

    <!-- 统计概览 -->
    <view class="overview-section">
      <view class="overview-grid">
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.totalMembers }}</text>
          <text class="overview-label">总人数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.attendanceRate }}%</text>
          <text class="overview-label">出勤率</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.todayAttendance }}</text>
          <text class="overview-label">今日出勤</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.todayAbsent }}</text>
          <text class="overview-label">今日缺勤</text>
        </view>
      </view>
    </view>

    <!-- 统计类型切换 -->
    <view class="stats-type-section">
      <view class="type-tabs">
        <view 
          class="type-tab"
          :class="{ active: statsType === 'date' }"
          @click="switchStatsType('date')"
        >
          <text>按日期统计</text>
        </view>
        <view 
          class="type-tab"
          :class="{ active: statsType === 'shift' }"
          @click="switchStatsType('shift')"
        >
          <text>按班次统计</text>
        </view>
        <view 
          class="type-tab"
          :class="{ active: statsType === 'person' }"
          @click="switchStatsType('person')"
        >
          <text>按人员统计</text>
        </view>
        <view 
          class="type-tab"
          :class="{ active: statsType === 'today' }"
          @click="switchStatsType('today')"
        >
          <text>今日考勤</text>
        </view>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-section" v-if="statsType !== 'today'">
      <view class="filter-row">
        <!-- 日期筛选 -->
        <view class="filter-item" v-if="statsType === 'date' || statsType === 'shift'">
          <text class="filter-label">日期范围:</text>
          <picker 
            mode="date" 
            :value="filterData.startDate"
            @change="onStartDateChange"
          >
            <view class="picker-display">
              <text>{{ filterData.startDate || '开始日期' }}</text>
            </view>
          </picker>
          <text class="filter-separator">至</text>
          <picker 
            mode="date" 
            :value="filterData.endDate"
            @change="onEndDateChange"
          >
            <view class="picker-display">
              <text>{{ filterData.endDate || '结束日期' }}</text>
            </view>
          </picker>
        </view>

        <!-- 班次筛选 -->
        <view class="filter-item" v-if="statsType === 'shift' || statsType === 'person'">
          <text class="filter-label">班次:</text>
          <picker 
            :value="selectedShiftIndex" 
            :range="shiftList" 
            range-key="name"
            @change="onShiftChange"
          >
            <view class="picker-display">
              <text>{{ selectedShift.name || '全部班次' }}</text>
            </view>
          </picker>
        </view>

        <!-- 人员筛选 -->
        <view class="filter-item" v-if="statsType === 'person'">
          <text class="filter-label">人员:</text>
          <picker 
            :value="selectedMemberIndex" 
            :range="memberList" 
            range-key="name"
            @change="onMemberChange"
          >
            <view class="picker-display">
              <text>{{ selectedMember.name || '全部人员' }}</text>
            </view>
          </picker>
        </view>
      </view>

      <view class="search-row">
        <up-button class="query-btn" @click="queryStats">
          <image class="icon-image-small" src="/static/icons/search.svg" mode="aspectFit" />
          <text>查询</text>
        </up-button>
        <up-button class="refresh-btn" @click="refreshData">
          <image class="icon-image-small" src="/static/icons/reload.svg" mode="aspectFit" />
          <text>刷新</text>
        </up-button>
      </view>
    </view>

    <!-- 统计结果展示 -->
    <view class="stats-content">
      <!-- 按日期统计 -->
      <view v-if="statsType === 'date'" class="date-stats">
        <view class="stats-list">
          <view 
            v-for="(item, index) in dateStatsData" 
            :key="index" 
            class="stats-item"
          >
            <view class="stats-header">
              <text class="stats-date">{{ item.date }}</text>
              <text class="stats-rate">出勤率: {{ item.attendanceRate }}%</text>
            </view>
            <view class="stats-detail">
              <text class="detail-item">出勤: {{ item.attendance }}人</text>
              <text class="detail-item">缺勤: {{ item.absent }}人</text>
              <text class="detail-item">请假: {{ item.leave }}人</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 按班次统计 -->
      <view v-if="statsType === 'shift'" class="shift-stats">
        <view class="stats-list">
          <view 
            v-for="(item, index) in shiftStatsData" 
            :key="index" 
            class="stats-item"
          >
            <view class="stats-header">
              <text class="stats-shift">{{ item.shiftName }}</text>
              <text class="stats-rate">出勤率: {{ item.attendanceRate }}%</text>
            </view>
            <view class="stats-detail">
              <text class="detail-item">总天数: {{ item.totalDays }}天</text>
              <text class="detail-item">出勤: {{ item.attendance }}天</text>
              <text class="detail-item">缺勤: {{ item.absent }}天</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 按人员统计 -->
      <view v-if="statsType === 'person'" class="person-stats">
        <view class="stats-list">
          <view 
            v-for="(item, index) in personStatsData" 
            :key="index" 
            class="stats-item"
          >
            <view class="stats-header">
              <text class="stats-name">{{ item.name }}</text>
              <text class="stats-rate">出勤率: {{ item.attendanceRate }}%</text>
            </view>
            <view class="stats-detail">
              <text class="detail-item">岗位: {{ item.position }}</text>
              <text class="detail-item">出勤: {{ item.attendance }}天</text>
              <text class="detail-item">缺勤: {{ item.absent }}天</text>
              <text class="detail-item">请假: {{ item.leave }}天</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 今日考勤 -->
      <view v-if="statsType === 'today'" class="today-stats">
        <view class="today-summary">
          <text class="summary-title">今日考勤概况 ({{ todayDate }})</text>
          <view class="summary-grid">
            <view class="summary-item">
              <text class="summary-value">{{ todayStatsData.totalScheduled }}</text>
              <text class="summary-label">应到人数</text>
            </view>
            <view class="summary-item">
              <text class="summary-value">{{ todayStatsData.actualAttendance }}</text>
              <text class="summary-label">实到人数</text>
            </view>
            <view class="summary-item">
              <text class="summary-value">{{ todayStatsData.leaveCount }}</text>
              <text class="summary-label">请假人数</text>
            </view>
            <view class="summary-item">
              <text class="summary-value">{{ todayStatsData.absentCount }}</text>
              <text class="summary-label">缺勤人数</text>
            </view>
          </view>
        </view>

        <view class="today-list">
          <view 
            v-for="(item, index) in todayAttendanceList" 
            :key="index" 
            class="today-item"
            :class="item.status"
          >
            <view class="today-info">
              <text class="today-name">{{ item.name }}</text>
              <text class="today-position">{{ item.position }}</text>
            </view>
            <view class="today-status">
              <text class="status-text" :class="item.status">{{ getStatusText(item.status) }}</text>
              <text class="today-time" v-if="item.checkInTime">{{ item.checkInTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <text>加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const loading = ref(false)
const statsType = ref('date') // date, shift, person, today

// 概览数据
const overviewData = reactive({
  totalMembers: 0,
  attendanceRate: 0,
  todayAttendance: 0,
  todayAbsent: 0
})

// 筛选条件
const filterData = reactive({
  startDate: '',
  endDate: '',
  shiftId: '',
  memberId: ''
})

// 班次列表
const shiftList = ref([])
const selectedShiftIndex = ref(0)
const selectedShift = computed(() => shiftList.value[selectedShiftIndex.value] || {})

// 人员列表
const memberList = ref([])
const selectedMemberIndex = ref(0)
const selectedMember = computed(() => memberList.value[selectedMemberIndex.value] || {})

// 统计数据
const dateStatsData = ref([])
const shiftStatsData = ref([])
const personStatsData = ref([])
const todayStatsData = reactive({
  totalScheduled: 0,
  actualAttendance: 0,
  leaveCount: 0,
  absentCount: 0
})
const todayAttendanceList = ref([])

// 今日日期
const todayDate = computed(() => {
  const today = new Date()
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
})

// 页面加载
onLoad(() => {
  initData()
})

onMounted(() => {
  loadMockData()
})

// 初始化数据
const initData = () => {
  const today = new Date()
  const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  
  filterData.startDate = `${lastWeek.getFullYear()}-${String(lastWeek.getMonth() + 1).padStart(2, '0')}-${String(lastWeek.getDate()).padStart(2, '0')}`
  filterData.endDate = todayDate.value
}

// 加载模拟数据
const loadMockData = () => {
  // 模拟班次数据
  shiftList.value = [
    { id: '', name: '全部班次' },
    { id: '1', name: '早班 (08:00-16:00)' },
    { id: '2', name: '中班 (16:00-24:00)' },
    { id: '3', name: '夜班 (00:00-08:00)' }
  ]

  // 模拟人员数据
  memberList.value = [
    { id: '', name: '全部人员' },
    { id: '1', name: '张三', position: '巡检员' },
    { id: '2', name: '李四', position: '巡检员' },
    { id: '3', name: '王五', position: '巡检员' },
    { id: '4', name: '赵六', position: '巡检员' }
  ]

  // 模拟概览数据
  overviewData.totalMembers = 12
  overviewData.attendanceRate = 92
  overviewData.todayAttendance = 11
  overviewData.todayAbsent = 1

  // 根据当前统计类型加载对应数据
  loadStatsData()
}

// 加载统计数据
const loadStatsData = () => {
  switch (statsType.value) {
    case 'date':
      loadDateStats()
      break
    case 'shift':
      loadShiftStats()
      break
    case 'person':
      loadPersonStats()
      break
    case 'today':
      loadTodayStats()
      break
  }
}

// 加载按日期统计数据
const loadDateStats = () => {
  // 模拟按日期统计数据
  dateStatsData.value = [
    {
      date: '2024-01-15',
      attendance: 11,
      absent: 1,
      leave: 0,
      attendanceRate: 92
    },
    {
      date: '2024-01-14',
      attendance: 12,
      absent: 0,
      leave: 0,
      attendanceRate: 100
    },
    {
      date: '2024-01-13',
      attendance: 10,
      absent: 2,
      leave: 0,
      attendanceRate: 83
    }
  ]
}

// 加载按班次统计数据
const loadShiftStats = () => {
  // 模拟按班次统计数据
  shiftStatsData.value = [
    {
      shiftName: '早班 (08:00-16:00)',
      totalDays: 7,
      attendance: 6,
      absent: 1,
      attendanceRate: 86
    },
    {
      shiftName: '中班 (16:00-24:00)',
      totalDays: 7,
      attendance: 7,
      absent: 0,
      attendanceRate: 100
    },
    {
      shiftName: '夜班 (00:00-08:00)',
      totalDays: 7,
      attendance: 6,
      absent: 1,
      attendanceRate: 86
    }
  ]
}

// 加载按人员统计数据
const loadPersonStats = () => {
  // 模拟按人员统计数据
  personStatsData.value = [
    {
      name: '张三',
      position: '巡检员',
      attendance: 7,
      absent: 0,
      leave: 0,
      attendanceRate: 100
    },
    {
      name: '李四',
      position: '巡检员',
      attendance: 6,
      absent: 1,
      leave: 0,
      attendanceRate: 86
    },
    {
      name: '王五',
      position: '巡检员',
      attendance: 7,
      absent: 0,
      leave: 0,
      attendanceRate: 100
    }
  ]
}

// 加载今日考勤数据
const loadTodayStats = () => {
  // 模拟今日统计数据
  todayStatsData.totalScheduled = 12
  todayStatsData.actualAttendance = 11
  todayStatsData.leaveCount = 0
  todayStatsData.absentCount = 1

  // 模拟今日考勤列表
  todayAttendanceList.value = [
    {
      name: '张三',
      position: '巡检员',
      status: 'present',
      checkInTime: '08:15'
    },
    {
      name: '李四',
      position: '巡检员',
      status: 'present',
      checkInTime: '08:20'
    },
    {
      name: '王五',
      position: '巡检员',
      status: 'absent',
      checkInTime: ''
    },
    {
      name: '赵六',
      position: '巡检员',
      status: 'present',
      checkInTime: '08:10'
    }
  ]
}

// 切换统计类型
const switchStatsType = (type: string) => {
  statsType.value = type
  loadStatsData()
}

// 日期选择事件
const onStartDateChange = (e: any) => {
  filterData.startDate = e.detail.value
}

const onEndDateChange = (e: any) => {
  filterData.endDate = e.detail.value
}

// 班次选择事件
const onShiftChange = (e: any) => {
  selectedShiftIndex.value = e.detail.value
  filterData.shiftId = selectedShift.value.id
}

// 人员选择事件
const onMemberChange = (e: any) => {
  selectedMemberIndex.value = e.detail.value
  filterData.memberId = selectedMember.value.id
}

// 查询统计
const queryStats = () => {
  loading.value = true
  setTimeout(() => {
    loadStatsData()
    loading.value = false
  }, 1000)
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loadMockData()
    loading.value = false
  }, 500)
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    present: '已到岗',
    absent: '缺勤',
    leave: '请假',
    late: '迟到'
  }
  return statusMap[status] || '未知'
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.attendance-stats-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// 导航栏样式
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44px 16px 12px;
  background-color: #ffffff;
  border-bottom: 1px solid #e5e5e5;

  .icon-image {
    width: 24px;
    height: 24px;
  }

  .navbar-title {
    font-size: 18px;
    font-weight: 600;
    color: #333333;
  }

  .navbar-right {
    width: 24px;
  }
}

// 概览区域样式
.overview-section {
  padding: 16px;
  background-color: #ffffff;
  margin-bottom: 8px;

  .overview-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
  }

  .overview-item {
    text-align: center;

    .overview-value {
      display: block;
      font-size: 24px;
      font-weight: 600;
      color: #4D6EE7;
      margin-bottom: 4px;
    }

    .overview-label {
      font-size: 12px;
      color: #666666;
    }
  }
}

// 统计类型切换样式
.stats-type-section {
  padding: 16px;
  background-color: #ffffff;
  margin-bottom: 8px;

  .type-tabs {
    display: flex;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #e5e5e5;
  }

  .type-tab {
    flex: 1;
    padding: 12px 8px;
    text-align: center;
    background-color: #f8f9fa;
    border-right: 1px solid #e5e5e5;
    cursor: pointer;
    transition: all 0.3s;

    &:last-child {
      border-right: none;
    }

    &.active {
      background-color: #4D6EE7;
      color: #ffffff;
    }

    text {
      font-size: 14px;
    }
  }
}

// 筛选区域样式
.filter-section {
  padding: 16px;
  background-color: #ffffff;
  margin-bottom: 8px;

  .filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 12px;
  }

  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    min-width: 200px;

    .filter-label {
      font-size: 14px;
      color: #333333;
      white-space: nowrap;
    }

    .filter-separator {
      font-size: 14px;
      color: #666666;
      margin: 0 4px;
    }

    .picker-display {
      flex: 1;
      padding: 8px 12px;
      border: 1px solid #e5e5e5;
      border-radius: 4px;
      background-color: #ffffff;
      font-size: 14px;
      color: #333333;
    }
  }

  .search-row {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .query-btn,
  .refresh-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    border: none;
    cursor: pointer;
  }

  .query-btn {
    background-color: #4D6EE7;
    color: #ffffff;
  }

  .refresh-btn {
    background-color: #f8f9fa;
    color: #333333;
    border: 1px solid #e5e5e5;
  }

  .icon-image-small {
    width: 16px;
    height: 16px;
  }
}

// 统计内容样式
.stats-content {
  padding: 0 16px;

  .stats-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .stats-item {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e5e5e5;

    .stats-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .stats-date,
      .stats-shift,
      .stats-name {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      .stats-rate {
        font-size: 14px;
        color: #4D6EE7;
        font-weight: 600;
      }
    }

    .stats-detail {
      display: flex;
      gap: 16px;
      flex-wrap: wrap;

      .detail-item {
        font-size: 14px;
        color: #666666;
      }
    }
  }
}

// 今日考勤样式
.today-stats {
  .today-summary {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    border: 1px solid #e5e5e5;

    .summary-title {
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      margin-bottom: 12px;
      display: block;
    }

    .summary-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 12px;
    }

    .summary-item {
      text-align: center;

      .summary-value {
        display: block;
        font-size: 20px;
        font-weight: 600;
        color: #4D6EE7;
        margin-bottom: 4px;
      }

      .summary-label {
        font-size: 12px;
        color: #666666;
      }
    }
  }

  .today-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .today-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e5e5e5;

    &.present {
      border-left: 4px solid #52c41a;
    }

    &.absent {
      border-left: 4px solid #ff4d4f;
    }

    &.leave {
      border-left: 4px solid #faad14;
    }

    .today-info {
      .today-name {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
        display: block;
        margin-bottom: 4px;
      }

      .today-position {
        font-size: 14px;
        color: #666666;
      }
    }

    .today-status {
      text-align: right;

      .status-text {
        font-size: 14px;
        font-weight: 600;
        display: block;
        margin-bottom: 4px;

        &.present {
          color: #52c41a;
        }

        &.absent {
          color: #ff4d4f;
        }

        &.leave {
          color: #faad14;
        }
      }

      .today-time {
        font-size: 12px;
        color: #666666;
      }
    }
  }
}

// 加载状态样式
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;

  .loading-content {
    background-color: #ffffff;
    padding: 20px 30px;
    border-radius: 8px;
    text-align: center;

    text {
      font-size: 16px;
      color: #333333;
    }
  }
}
</style>